import axios from 'axios'
import store from '@/store'
import { getToken } from '@/utils/auth'
import constants from '@/utils/constants'
// import RSAEncrypt from '@/utils/RSAEncrypt'
import { Toast, Dialog, Notify } from 'vant'

let loadingInstance = null
const service = axios.create({
  baseURL: process.env.NODE_ENV === 'development' ? process.env.VUE_APP_BASE_API : window.g.baseURL,
  timeout: 1000 * 60
})

service.interceptors.request.use(
  config => {
    var loading = true
    if (config.method === 'get') {
      if (config.params != null) {
        if (config.params.loading != null) {
          loading = config.params.loading
        }
      }
      config.params = {
        _t: Date.parse(new Date()) / 1000,
        ...config.params
      }
    }
    if (config.method === 'post') {
      if (config.data != null) {
        if (config.data instanceof FormData) {
          if (config.data.has('loading')) {
            loading = config.data.get('loading')
          }
        }
        if (config.data.loading != null) {
          loading = config.data.loading
        }
      }
    }
    if (loading) {
      loadingInstance = Toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        message: '请求中...'
      })
    }
    if (store.getters.token) {
      config.headers['Access-Token'] = getToken()
    }
    config.headers['ProjectsId'] = constants.PROJECTS_ID
    config.headers['App-Id'] = constants.APP_ID
    config.headers['App-Key'] = constants.APP_KEY
    config.headers['Sign'] = 'MD5='
    return config
  },
  error => {
    if (loadingInstance) {
      Toast.clear()
    }
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const res = response.data
    if (loadingInstance) {
      Toast.clear()
    }
    if (res instanceof ArrayBuffer) {
      var resultBufferString = String.fromCharCode.apply(null, new Uint8Array(res))
      if (resultBufferString.toLocaleLowerCase().indexOf('png') > -1 || resultBufferString.toLocaleLowerCase().indexOf('jfif') > -1) {
        return 'data:image/png;base64,' + btoa(new Uint8Array(res).reduce((data, byte) => data + String.fromCharCode(byte), ''))
      } else {
        resultBufferString = decodeURIComponent(escape(resultBufferString))
        resultBufferString = JSON.parse(resultBufferString)
        Notify({ type: 'warning', message: resultBufferString.data == null ? resultBufferString.message : resultBufferString.data })
      }
    } else if (res instanceof Blob) {
      if (res.type === 'application/json') {
        const reader = new FileReader()
        reader.addEventListener('loadend', function() {
          var json = JSON.parse(reader.result)
          if (!json.success) {
            Notify({ type: 'warning', message: json.data == null ? json.message : json.data })
          }
        })
        reader.readAsText(res, 'UTF-8')
        res.contentType = 'json'
      } else {
        var fileName = response.headers['download-filename']
        if (fileName) {
          fileName = response.headers['content-disposition']
          if (fileName) {
            fileName = fileName.replace('attachment; filename=', '')
          }
        }
        res.fileName = decodeURI(fileName)
        res.contentType = 'blob'
      }
      return res
    } else {
      if (response.config.url.indexOf('/actuator/') > -1) {
        return res
      }
      if (res.code !== 200) {
        if (res.code === 500) {
          if (res.data.requestId) {
            var message = `
            错误代码:【${res.data.errorCode}】\n
            请求码:【${res.data.requestId}】\n
            错误描述:【${res.data.errorMessage}】${res.data.errorLocalizedMessage}</m>\n
            备注:请将请求码发送给管理员排查错误!您的反馈将是我们不断进步的动力!\n`
            Dialog.alert({
              title: '系统异常',
              message: message,
              confirmButtonText: '确定'
            }).then(() => {
            })
          } else {
            Notify({ type: 'warning', message: res.data == null ? res.message : res.data })
          }
        } else if (res.code === 501) {
          var html = ''
          var data = res.data
          for (var item in data) {
            html += `【${item}】：${data[item]}\n`
          }
          Notify({ type: 'warning', message: `${html}` })
        } else if (res.code === 506003) {
          Dialog.alert({
            title: '系统提示',
            message: '登录状态已过期需重新登录',
            confirmButtonText: '重新登录'
          }).then(() => {
            store.dispatch('removeToken').then(() => {
              location.href = '/#/dashboard'
            })
          })
        } else {
          Notify({ type: 'warning', message: res.data == null ? res.message : res.data })
        }

        return Promise.reject(res)
      } else {
        return res.data
      }
    }
  },
  error => {
    if (loadingInstance) {
      Toast.clear()
    }
    console.error('err', error) // for debug
    Notify({ type: 'danger', message: error.message === 'Network Error' ? '抱歉,服务忙,请稍后重试~' : error.message })
    return Promise.reject(error)
  }
)

service.get = (url, params = {}) => {
  return service({
    method: 'GET',
    url: url,
    params: params
  })
}
service.post = (url, params = {}) => {
  return service({
    method: 'POST',
    url: url,
    data: params,
    headers: {
      'Content-Type': 'application/json;charset=UTF-8'
    }
  })
}
service.pictureStream = (url, params) => {
  return service({
    method: 'GET',
    url: url,
    params: params,
    responseType: 'arraybuffer'
  })
}
/**
 * 文件下载
 */
service.downloadFile = (url, params) => {
  return service({
    method: 'POST',
    url: url,
    data: params,
    responseType: 'blob',
    headers: {
      'Content-Type': 'application/json;charset=UTF-8'
    }
  })
}

/**
 * 文件上传
 */
service.uploadFile = (url, params) => {
  return service({
    method: 'POST',
    url: url,
    data: params,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

export default service
